package cn.wizzer.app.web.modules.controllers.platform.bus;

import cn.wizzer.app.bus.modules.models.YJbxx;
import cn.wizzer.app.bus.modules.models.YJbxxJyxm;
import cn.wizzer.app.bus.modules.services.*;
import cn.wizzer.app.sys.modules.services.SysDictService;
import cn.wizzer.app.sys.modules.services.SysUnitService;
import cn.wizzer.app.sys.modules.services.SysUserService;
import cn.wizzer.app.web.commons.slog.annotation.SLog;
import cn.wizzer.app.web.commons.utils.StringUtil;
import cn.wizzer.framework.base.Result;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.adaptor.JsonAdaptor;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * 样品信息,admin全流程修改、删除  虞秀斌  2019-11
 */
@IocBean
@At("/platform/bus/ypxx/jbxxAdmin")
public class YJbxxAdminController {
    private static final Log log = Logs.get();
    @Inject
    private YJbxxService yjbxxService;
    @Inject
    private YJbxxLcxxService yjbxxlcxxservice;
    @Inject
    private YJbxxLzxxService yjbxxlzxxservice;
    @Inject
    private SysUnitService sysUnitService;
    @Inject
    private SysDictService sysDictService;
    @Inject
    private SysUserService sysUserService;
    @Inject
    private YJbxxSfjlService yjbxxsfjlservice;
    @Inject
    private YJbxxJyxmService yjbxxjyxmservice;

    @Inject
    private BusinessFileInfoService businessFileInfoService;


    @At("")
    @Ok("beetl:/platform/bus/ypxx/jbxxAdmin/list.html")
    @RequiresPermissions("bus.ypxx.jbxxAdmin.data")
    public void index(@Param("pageForm") String pageForm,HttpServletRequest req) {
        req.setAttribute("userId", StringUtil.getPlatformUid());
        req.setAttribute("jylxMap", JSONObject.fromObject(sysDictService.getCodeMap("jylx")));
        req.setAttribute("lcztMap", JSONObject.fromObject(sysDictService.getCodeMap("lczt")));
        req.setAttribute("lzztMap", JSONObject.fromObject(sysDictService.getCodeMap("lzzt")));
        req.setAttribute("lcztOptions", JSONArray.fromObject(sysDictService.dictCodeTree("lczt")));
        req.setAttribute("lzztOptions", JSONArray.fromObject(sysDictService.dictCodeTree("lzzt")));
        req.setAttribute("pageForm", JSONObject.fromObject(pageForm));
    }

    @At
    @Ok("json:{locked:'password|salt',ignoreNull:false}")
    @RequiresPermissions("bus.ypxx.jbxxAdmin.data")
    public Object data(@Param("searchKeyword") String searchKeyword,@Param("lczt") String lczt,@Param("lzzt") String lzzt,@Param("delflag") String delflag, @Param("pageNumber") int pageNumber,
                       @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
        try {
            String sql ="SELECT jbxx.id,jbxx.lzzt,jbxx.lczt, jbxx.ypbh,jbxx.bgbh, jbxx.ypmc,jbxx.status, jbxx.jylx, jbxx.jyks, jbxx.wtdw, jbxx.ggxh, jbxx.scrqpc, jbxx.sb, jbxx.wcqx, '' AS sysj, jbxx.jyfy, sfjl.ysfy, sfjl.jfrq,u.username,FROM_UNIXTIME(jbxx.opAt) as tjsj,jbxx.opBy,jbxx.delflag " +
                    " FROM y_jbxx jbxx LEFT JOIN ( SELECT jsfjl.ypbh, sum(jsfjl.bcss) AS ysfy, max(jsfjl.jfrq) AS jfrq FROM Y_Jbxx_sfjl jsfjl GROUP BY jsfjl.ypbh ) sfjl ON jbxx.ypbh = sfjl.ypbh " +
                    " left join sys_user u on u.id=jbxx.opBy  where 1=1 ";
            if (Strings.isNotBlank(searchKeyword)) {
                sql+= " and (jbxx.ypbh like '%"+searchKeyword+"%' or jbxx.ypmc like '%"+searchKeyword+"%') ";
            }
            if (Strings.isNotBlank(lczt)&&!lczt.equals("")) {
                sql+= " and jbxx.lczt = '"+lczt+"' ";
            }
            if (Strings.isNotBlank(lzzt)&&!lzzt.equals("")) {
                sql+= " and jbxx.lzzt = '"+lzzt+"' ";
            }
            if (Strings.isNotBlank(delflag)&&!delflag.equals("")) {
                sql+= " and jbxx.delflag = '"+delflag+"' ";
            }
            //只能查询自己登记的数据
            //sql+= " and jbxx.opBy = '"+StringUtil.getPlatformUid()+"' ";
            //这个功能是为了查询所有的数据，菜单分给谁，谁就可以操作，不限制权限
            //sql+= StringUtil.dataScopeFilter("jbxx");
            if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
                if ("ascending".equalsIgnoreCase(pageOrderBy)) {
                    sql+= " order by "+pageOrderName+" asc,jbxx.opAt desc ";
                } else {
                    sql+= " order by "+pageOrderName+" desc,jbxx.opAt desc ";
                }
            }else{
                sql+= " order by jbxx.opAt desc ";
            }
            return Result.success().addData(yjbxxService.listPage(pageNumber,pageSize, Sqls.create(sql)));
        } catch (Exception e) {
            return Result.error();
        }
    }

    @At("/edit/?")
    @Ok("beetl:/platform/bus/ypxx/jbxxAdmin/edit.html")
    @RequiresPermissions("bus.ypxx.jbxxAdmin.edit")
    @AdaptBy(type = JsonAdaptor.class)
    public void edit(String id,@Param("pageForm") String pageForm,HttpServletRequest req) {
        YJbxx obj = yjbxxService.fetchLinks(yjbxxService.fetch(id),"yjbxxjyxm",Cnd.NEW().asc("inspectionItemOrder"));
        req.setAttribute("obj",JSONObject.fromObject(obj));
        req.setAttribute("yplxOptions", JSONArray.fromObject(sysDictService.dictCodeTree("yplx")));
        req.setAttribute("zhOptions", JSONArray.fromObject(sysDictService.dictTree("zh")));
        List<NutMap> list = sysDictService.dictTreeChild("xzqh");
        if(StringUtils.isNotBlank(obj.getSzcs())){
            list = sysDictService.dictTreeChilds(obj.getSzcs().split(","),list);
        }

        req.setAttribute("szcsOptions", JSONArray.fromObject(list));
        req.setAttribute("pageForm", JSONObject.fromObject(pageForm));
        req.setAttribute("ypczOptions", JSONArray.fromObject(sysDictService.dictTree("ypcz")));
        req.setAttribute("jylxOptions", JSONArray.fromObject(sysDictService.dictCodeTree("jylx")));
        req.setAttribute("unitOptions", JSONArray.fromObject(sysUnitService.getJybmTree()));
        req.setAttribute("yplxMap", JSONObject.fromObject(sysDictService.getCodeMap("yplx")));
        req.setAttribute("storageOptions", JSONArray.fromObject(sysDictService.dictTree("storage")));
        req.setAttribute("informationOptions", JSONArray.fromObject(sysDictService.dictTree("information")));
        req.setAttribute("intentionOptions", JSONArray.fromObject(sysDictService.dictTree("intention")));
        req.setAttribute("exteriorOptions", JSONArray.fromObject(sysDictService.dictTree("exterior")));
    }

    @At
    @Ok("json")
    @RequiresPermissions("bus.ypxx.jbxxAdmin.edit")
    @SLog(tag = "全流程操作-编辑样品,不影响流程", msg = "样品:${args[0].ypbh}，id:${args[0].id}")
    public Object editDo(@Param("..") YJbxx obj) {
        try {
            int count = yjbxxService.count(Sqls.create("select count(1) from y_jbxx where ypbh = '" + obj.getYpbh()+"' and id !='"+obj.getId()+"' and delflag=0"));
            if(count>0) {//存在重复
                return Result.error("样品编号"+obj.getYpbh()+"重复,请修改！");
            }
            yjbxxService.update(obj);
            yjbxxjyxmservice.execute(Sqls.create("delete from y_jbxx_jyxm  where jbxxid='"+obj.getId()+"'"));
            for(YJbxxJyxm jyxm : obj.getYjbxxjyxm()){
                jyxm.setJbxxId(obj.getId());
                yjbxxjyxmservice.insert(jyxm);
            }
            return Result.success("全流程操作-编辑成功！");
        } catch (Exception e) {
            return Result.error("system.error");
        }
    }


    @At("/delete/?")
    @Ok("json")
    @RequiresPermissions("bus.ypxx.jbxxAdmin.delete")
    @SLog(tag = "全流程操作-删除样品", msg = "样品id:${args[0]}")
    public Object delete(String id, HttpServletRequest req) {
        try {
            yjbxxService.vDelete(id);
            yjbxxlzxxservice.clearCache();
            yjbxxlcxxservice.clearCache();
            return Result.success("删除成功！");
        } catch (Exception e) {
            return Result.error();
        }
    }

    @At("/delete")
    @Ok("json")
    @RequiresPermissions("bus.ypxx.jbxxAdmin.delete")
    @SLog(tag = "全流程操作-批量删除样品", msg = "IDS:${args[1].getAttribute('ids')}")
    public Object deletes(@Param("ids") String[] ids, HttpServletRequest req) {
        try {
            yjbxxService.vDelete(ids);
            yjbxxlzxxservice.clearCache();
            yjbxxlcxxservice.clearCache();
            req.setAttribute("ids", ids.toString());
            return Result.success("删除成功！");
        } catch (Exception e) {
            return Result.error();
        }
    }

    @At("/restore/?")
    @Ok("json")
    @RequiresPermissions("bus.ypxx.jbxxAdmin.restore")
    @SLog(tag = "全流程操作-恢复样品", msg = "样品id:${args[0]}")
    public Object restore(String id, HttpServletRequest req) {
        try {
            YJbxx obj =   yjbxxService.fetch(id);
            if(StringUtils.isNotEmpty(obj.getYpbh())) {
                int count = yjbxxService.count(Sqls.create("select count(1) from y_jbxx where ypbh = '" + obj.getYpbh() + "' and id !='" + obj.getId() + "' and delflag=0"));
                if (count > 0) {//存在重复
                    return Result.error("样品编号" + obj.getYpbh() + "重复,无法恢复，请修改后恢复！");
                }
            }
            if(StringUtils.isNotEmpty(obj.getBgbh())) {
                int countbgbh = yjbxxService.count(Sqls.create("select count(1) from y_jbxx where bgbh = '" + obj.getBgbh() + "' and id !='" + obj.getId() + "' and delflag=0"));
                if (countbgbh > 0) {//存在重复
                    return Result.error("报告编号" + obj.getBgbh() + "重复,无法恢复，请修改后恢复！");
                }
            }
            obj.setDelFlag(false);
            yjbxxService.update(obj);
            yjbxxlzxxservice.clearCache();
            yjbxxlcxxservice.clearCache();
            return Result.success("恢复成功！");
        } catch (Exception e) {
            return Result.error();
        }
    }



}
